<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader :list="list" @enter="enterFn" @isAll="isAllFn"></TodoHeader>
    <TodoMain :list="showList" @change="changeFn" @delete="delFn"></TodoMain>
    <TodoFooter :list="list" :task="task" @changeTask="changeTaskFn" @clear="clearFn"></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("taskStrList")) || [],
      /* [
        { id: 100, name: "吃饭", isDone: true },
        { id: 101, name: "睡觉", isDone: false },
        { id: 102, name: "打豆豆", isDone: true },
      ], */
      task: 'all' /* all 为全部  yes 已完成  no 未完成 */
    };
  },
  methods: {
    /* 接收 id ，根据id 修改 isDone 的值 */
    changeFn(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    delFn(id) {
      /* 根据id  删除当前项 */
      this.list = this.list.filter((item) => item.id != id);
    },

    enterFn(taskStr) {
      /* 添加数组元素 */
      this.list.push({
        /* 如果数组没有元素时 添加元素的id为1 */
        id: this.list.length > 0 ? this.list.at(-1).id + 1 : 1,
        name: taskStr,
        isDone: false,
      })
    },
    /* 修改list内每个对象内的isDone值 从而实现全选按钮 */
    isAllFn(val){
      this.list.forEach(item => item.isDone = val)
    },
    changeTaskFn(task){
      this.task = task
    },
    clearFn(){
      this.list = this.list.filter(item => !item.isDone)
    }
  },
  /* 监听属性 */
  watch: {
    /* 监听list */
    list: {
      deep:true,/* 深度监听 */
      handler() {
        localStorage.setItem("taskStrList", JSON.stringify(this.list));
      },
    },
  },
  /* 计算属性 */
  computed:{
    showList(){
      if(this.task === 'yes'){
        return this.list.filter( item => item.isDone )
      }else if(this.task === 'no'){
        return this.list.filter( item => !item.isDone )
      }else{
        return this.list
      }
    }
  }
};
</script>